package com.zhss.demo.redisson;

import com.zhss.demo.ConsolHelp;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.ReadMode;

import java.util.concurrent.TimeUnit;

public class RedissionHelp {
    private static volatile RedissonClient REDISSON_CLIENT;

    public static RedissonClient getRedissionClient() {
        if (REDISSON_CLIENT == null) {
            synchronized (RedissionHelp.class) {
                if (REDISSON_CLIENT == null) {
                    REDISSON_CLIENT = originGet();
                }
            }
        }
        return REDISSON_CLIENT;
    }

    private static RedissonClient originGet() {
        Config config = new Config();
        config.useClusterServers().setScanInterval(200)
                .addNodeAddress("redis://192.168.56.101:7001")
                .addNodeAddress("redis://192.168.56.101:7002")
                .addNodeAddress("redis://192.168.56.101:7003")
                .addNodeAddress("redis://192.168.56.101:7004")
                .addNodeAddress("redis://192.168.56.101:7005")
                .addNodeAddress("redis://192.168.56.101:7006")
                .setPassword("redis").setReadMode(ReadMode.MASTER);

        return Redisson.create(config);
    }

    public static void shutdown(RedissonClient redissonClient) {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        redissonClient.shutdown();
    }

    public static <T> void wait(T semaphore, RedissonClient redissonClient) {
        while (true) {
            String command = ConsolHelp.get();
            if ("close".equals(command)) {
                break;
            } else {
                System.err.println(command);
            }
        }
        RedissionHelp.shutdown(redissonClient);
    }

}
